
import time
import hmac
import hashlib
import base64
import urllib.parse
import requests

DD_WEBHOOK = None
DD_SECRET = None

def get_sign(secret, timestamp):
  secret_enc = secret.encode('utf-8')
  string_to_sign = '{}\n{}'.format(timestamp, secret)
  string_to_sign_enc = string_to_sign.encode('utf-8')
  hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
  sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
  print(sign)
  return sign


def send_text(webhook, secret, content):
  print(secret)
  webhook = str(webhook).strip()
  secret = str(secret).strip()
  timestamp = str(round(time.time() * 1000))
  url = "{}&sign={}&timestamp={}"
  headers = {'Content-Type': 'application/json'}
  data = {"msgtype": "text","text": {"content":str(content)}}
  sign = get_sign(secret, timestamp)
  url = url.format(webhook, sign, timestamp)
  print(url)
  resp = requests.post(url, json=data, headers=headers)
  print(resp.text)
  return resp
